﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using QLZJFurnitureSCM.BLL;
using QLZJFurnitureSCM.Model;
using System.IO;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.Configuration;
using System.Collections.Specialized;

namespace QLZJFurnitureSCM.WinForm
{
    public partial class FrmOrder : Form
    {
        private ProductService productService = null;
        private FurnitureTypeService furnitureTypeService = null;
        private ContactService contactService = null;
        private EmployeeService employeeService = null;
        private OrderService orderService = null;
        private OrderProductService orderProductService = null;
        private List<Product> lstProduct = null;
        private List<FurnitureType> lstFurnitrueType = null;
        private List<Contact> lstContact = null;
        private List<Employee> lstEmployee = null;
        private System.Data.DataTable dtOrderProducts = null;
        private Product productSell = null;

        private int _totalCount;
        private decimal _totalPrice;
        private decimal _percentPrice;
        public FrmOrder()
        {
            InitializeComponent();
            productService = new ProductService();
            furnitureTypeService = new FurnitureTypeService();
            contactService = new ContactService();
            employeeService = new EmployeeService();
            orderService = new OrderService();
            orderProductService = new OrderProductService();
        }

        public FrmOrder(Product product):this()
        {
            this.productSell = product;
        }

        private void FrmOrder_Load(object sender, EventArgs e)
        {
            InitProducts();
            InitTypes();
            InitContacts();
            InitEmployees();
            this.dtpRender.Value = DateTime.Now;
        }

        private void InitTypes()
        {
            List<FurnitureType> lstFurnitrueTypeAll = furnitureTypeService.ReadAll();
            List<int> lstProductType = (from p in lstProduct select p.ProductType).ToList();
            FurnitureType single = null;
            lstFurnitrueType = new List<FurnitureType>();
            if (lstFurnitrueTypeAll.Count == 0)
            {
                MessageBox.Show("没有任何产品类别, 请先添加");
                return;
            }
            foreach(int type in lstProductType){
                single = (from furniture in lstFurnitrueTypeAll where furniture.TypeId == type select furniture).FirstOrDefault();
                if(null != single)
                    lstFurnitrueType.Add(single);
            }
                //(from p in lstProduct select p.ProductType)
            
            cboType.Items.AddRange(lstFurnitrueType.Distinct().ToArray());
            cboType.DisplayMember = "TypeName";
            cboType.ValueMember = "TypeId";
            if (cboType.Items.Count > 0)
                cboType.SelectedIndex = 0;
        }

        private void InitProducts()
        {
            lstProduct = productService.ReadAll();
        }

        private void InitContacts()
        {
            lstContact = contactService.FindAllContacts();
            if (lstContact.Count > 0)
            {
                this.cboContacts.Items.AddRange(lstContact.ToArray());
                this.cboContacts.DisplayMember = "ContactName";
                this.cboContacts.ValueMember = "ContactId";
                this.cboContacts.SelectedIndex = 0;
            }
        }

        private void InitEmployees()
        {
            lstEmployee = employeeService.FindAllEmployee();
            List<Employee> lstDriverEmployees = (from e in lstEmployee where e.EmployeeCanDrive == true select e).ToList();
            if(lstDriverEmployees.Count > 0)
            {
                this.cboDriver.Items.AddRange(lstDriverEmployees.ToArray());
                this.cboDriver.DisplayMember = "EmployeeName";
                this.cboDriver.ValueMember = "EmployeeId";
                this.cboDriver.SelectedIndex = 0;
            }
        }

        private void InitDataTable()
        {
            dtOrderProducts = new System.Data.DataTable("OrderProducts");
            //dtOrderProducts.Columns.a
        }

        private void cboType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //get Products by typeId;
            cboProducts.Items.Clear();
            txtPrice.Clear();
            //txtDescription.Clear();
            //txtAccumulate.Clear();
            //this can build a method in service.
            List<Product> lstProductByType = (from product in lstProduct where product.ProductType == ((FurnitureType)cboType.SelectedItem).TypeId select product).ToList();
            if (lstProductByType.Count > 0)
            {
                cboProducts.Items.AddRange(lstProductByType.ToArray());
                cboProducts.DisplayMember = "ProductName";
                cboProducts.ValueMember = "ProductId";
                cboProducts.SelectedIndex = 0;
            }
        }

        private void cboProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            //change the price;

            if (null != cboProducts.SelectedItem)
            {
                Product product = ((Product)cboProducts.SelectedItem);
                if (product != null)
                {
                    this.txtPrice.Text = product.ProductPriceSale.ToString();
                    this.txtDimension.Text = product.ProductDimension;
                    this.numericUpDownBuyCount.Maximum = product.ProductCountAccumulate;
                    //txtDescription.Text = product.ProductDescription;
                    //txtAccumulate.Text = product.ProductCount.ToString();
                }
            }
        }

        private void cboContacts_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowContactInfo();
        }

        private void ShowContactInfo()
        {
            object o = this.cboContacts.SelectedItem;
            if (null != o)
            {
                Contact contact = o as Contact;
                this.txtContactName.Text = contact.ContactName;
                this.txtContactPhoneNo.Text = contact.ContactPhone;
                this.txtContactDiscount.Text = contact.ContactDiscount.ToString();
                this.txtContactAddr.Text = contact.ContactAddress;
                this.SetControlState(true);
            }
        }


        private void initPrintDocTemplate()
        {

        }

        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {

        }

        private List<Product> lstProductSell = null;

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            this.btnPrintPreview.Enabled = false;
            /*
            PageSetupDialog needs a PageSettings object to display. 
            Set PageSetupDialog.Document (preferred), 
            PageSetupDialog.PrinterSettings, or PageSetupDialog.PageSettings.
            this.pageSetupDialogFrmOrder.ShowDialog();
             */
            //bnPrint_Click(sender, e);

            //验证
            string contactName = this.txtContactName.Text.Trim();
            string contactPhone = this.txtContactPhoneNo.Text.Trim();
            string contactAddr = this.txtContactAddr.Text.Trim();
            if(string.IsNullOrEmpty(contactPhone.Trim()) || string.IsNullOrEmpty(contactAddr))
            {
                MessageBox.Show("请完整填写客户信息", "错误");
                this.btnPrintPreview.Enabled = true;
                return;
            }
            string discountStr = this.txtContactDiscount.Text;
            decimal contactDiscount;
            if (string.IsNullOrEmpty(discountStr) || !decimal.TryParse(discountStr, out contactDiscount))
                contactDiscount = 0;
            else
                contactDiscount = decimal.Parse(discountStr);

            if (!rdoPayNow.Checked && !rdoPayRender.Checked)
            {
                MessageBox.Show("请先选择支付方式.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btnPrintPreview.Enabled = true;
                return;
            }
            
            if(this.cboDriverChoose.Items.Count == 0)
            {
                if (DialogResult.Yes == MessageBox.Show("确认不需要司机配货? \n需要请选择\"Yes\"\n继续请选择\"No\"", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    this.cboDriverChoose.Focus();
                    this.btnPrintPreview.Enabled = true;
                    return;
                }
            }

            if(dgvOrderProducts.Rows.Count <= 0)
            {
                this.toolStripStatusLabelFrmOrder.Text = "订单中没有商品, 请先添加.";
                this.btnPrintPreview.Enabled = true;
                return;
            }

            lstProductSell = new List<Product>();
            //MessageBox.Show(CreateWordFile());
            //return;
            /*
            int nameIndex = dgvOrderProducts.Columns["colProductName"].Index;
            int dimensionIndex = dgvOrderProducts.Columns["colProductDimension"].Index;
            int countIndex = dgvOrderProducts.Columns["colCount"].Index;
            int priceIndex = dgvOrderProducts.Columns["colPrice"].Index;

            foreach (DataGridViewRow row in dgvOrderProducts.Rows)
            {
                row.Cells[nameIndex].Value.ToString() ;
                row.Cells[dimensionIndex].Value.ToString();
                row.Cells[countIndex].Value.ToString();
                row.Cells[priceIndex].Value.ToString();
            }*/

            //InsertInto Database
            orderNo = DateTime.Now.ToString("yyMMddHHmmss");
                //Math.Abs(DateTime.Now.GetHashCode()).ToString();

            //string contactName = txtContactName.Text;
            //update address?            implement under
            //insert a new contact
            
            string drivers = string.Empty;
            foreach (string driver in lstDriver)
            {
                drivers += driver + "|";
            }
            if (!string.IsNullOrEmpty(drivers))
                drivers = drivers.Remove(drivers.Length - 1);
            else
                drivers = "无";
            string opUser = FrmMain.user.NickName;
            decimal orderPay = 0.0M;
            string price = this.lblPercentPrice.Text.Replace("元", "");
            if (chkUsePercent.Checked)
                orderPay = decimal.Parse(price.Trim());
            else
                orderPay =  _totalPrice;

            Order order = new Order();
            order.OrderByUser = opUser;
            order.OrderNo = orderNo;
            order.OrderDriveEmployee = drivers;
            order.OrderTime = DateTime.Now;
            order.OrderContact = contactName;
            order.OrderPayStatus = this.rdoPayNow.Checked;
            order.OrderPay = orderPay;

            orderService.Insert(order);

            if (order.OrderId > 0)
            {
                //insert into OrderProducts
                int nameIndex = dgvOrderProducts.Columns["colProductName"].Index;
                int dimensionIndex = dgvOrderProducts.Columns["colProductDimension"].Index;
                int countIndex = dgvOrderProducts.Columns["colCount"].Index;
                int priceIndex = dgvOrderProducts.Columns["colPrice"].Index;
                int productIdIndex = dgvOrderProducts.Columns["colProductId"].Index;
                List<OrderProduct> lstOrderProduct = new List<OrderProduct>();
                OrderProduct orderProduct = null;

                Product productRecordBuyCount = null;
                for (int i = 0; i < dgvOrderProducts.RowCount; i++)
                {
                    orderProduct = new OrderProduct();
                    orderProduct.OrderId = order.OrderId;
                    orderProduct.OrderNo = order.OrderNo;
                    orderProduct.ProductName = dgvOrderProducts[nameIndex, i].Value.ToString();
                    orderProduct.Dimension = dgvOrderProducts[dimensionIndex, i].Value.ToString();
                    int buyCount = int.Parse(dgvOrderProducts[countIndex, i].Value.ToString());
                    orderProduct.BuyCount = buyCount;
                    orderProduct.Price = decimal.Parse(dgvOrderProducts[priceIndex, i].Value.ToString());
                    int pId = int.Parse(dgvOrderProducts[productIdIndex, i].Value.ToString()); ;
                    orderProduct.ProductId = pId;
                    lstOrderProduct.Add(orderProduct);
                    productRecordBuyCount = new Product();
                    productRecordBuyCount.ProductId = pId;
                    productRecordBuyCount.ProductCountSale = buyCount; 
                    lstProductSell.Add(productRecordBuyCount);
                }
                if (orderProductService.InsertBatch(lstOrderProduct))
                {
                    toolStripStatusLabelFrmOrder.Text = "下单成功.";

                    //更新联系人;
                    Contact contact = new Contact();
                    contact.ContactName = contactName;
                    contact.ContactPhone = contactPhone;
                    contact.ContactAddress = contactAddr;
                    contact.ContactDiscount = contactDiscount;

                    //另起线程
                    if (this.rdoContactNew.Checked)//insert
                    {
                        if (contactService.Insert(contact).ContactId > 0)
                            this.toolStripStatusLabelFrmOrder.Text = "储存客户信息成功.";
                    }
                    else if (this.rdoAddrNew.Checked)//update
                    {
                        contact.ContactId = ((Contact)this.cboContacts.SelectedItem).ContactId;
                        if (contactService.Update(contact))
                            this.toolStripStatusLabelFrmOrder.Text = "更新客户信息成功.";
                    }

                    //库存--
                    //另起线程
                    List<Product> lstProductCountUpdate = new List<Product>();
                    Product temp = null;
                    foreach (OrderProduct ordPro in lstOrderProduct)
                    {
                        temp = new Product();
                        temp.ProductId = ordPro.ProductId;
                        temp.ProductCountAccumulate = ordPro.BuyCount;
                        //new add
                        temp.ProductCountSale = ordPro.BuyCount;
                        Console.WriteLine("{0}:{1}.", temp.ProductCountAccumulate, temp.ProductCountSale);
                        lstProductCountUpdate.Add(temp);
                    }
                    if (productService.UpdateProductCountBatch(lstProductCountUpdate))
                    {
                        this.toolStripStatusLabelFrmOrder.Text = "销售信息入库成功";
                    }
                    else
                    {
                        this.toolStripStatusLabelFrmOrder.Text = "销售信息入库失败, 请检查.";
                        return;
                    }
                   
                    Type wordApp = Type.GetTypeFromProgID("Word.Application");
                    MessageBox.Show("恭喜您, 下单成功!", "提示");
                    if (chkNeedPrint.Checked)
                    {
                        if (null == wordApp)
                        {
                            MessageBox.Show("抱歉\n检测到运行该应用程序的机器上并没有安装Microsoft Office Word 2003/2007 组件\n此将导致无法打印.");
                            return;
                        }
                        toolStripStatusLabelFrmOrder.Text = "正在打印...";
                        SendIntoOfficeWord(orderNo, opUser, contactName, drivers);
                    }
                    //reset controls
                    this.Invoke(new ResetControlsDelegate(ResetControls));
                    //this.Close();
                }
                else
                    lstProductSell = null;
            }else
                toolStripStatusLabelFrmOrder.Text = "下单失败, 请正确填写相关信息重试.";

            this.btnPrintPreview.Enabled = true;
            
            //PrintUsingFramework();
        }

        private delegate void ResetControlsDelegate();

        private void ResetControls()
        {
            //IEnumerable<Product> enumProduct = (IEnumerable<Product>)cboProducts.Items.GetEnumerator();

            foreach(Product p in lstProductSell)
            {
                //(from o in enumProduct where o.ProductId == p.ProductId select o.ProductCountAccumulate = o.ProductCountAccumulate - p.ProductCountSale).ToList();
                //foreach (Product pro in enumProduct)
                foreach (Product pro in lstProduct)
                {
                    if (pro.ProductId == p.ProductId)
                    {
                        pro.ProductCountAccumulate -= p.ProductCountSale;
                        break;
                    }
                }
            }

            //lstProduct = productService.ReadAll();

            cboProducts.Items.Clear();
            cboProducts.Items.AddRange(lstProduct.ToArray());

            dgvOrderProducts.Rows.Clear();
            this.cboType.SelectedIndex = 0;
            this.chkPriceUserDefine.Checked = false;
            this.chkUsePercent.Checked = false;
            this._percentPrice = 0M;
            this._totalCount = 0;
            this._totalPrice = 0M;
        }


        private void chkPriceUserDefine_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkPriceUserDefine.Checked)
                this.txtPrice.ReadOnly = false;
            else
                this.txtPrice.ReadOnly = true;
        }

        private void rdoContactNew_CheckedChanged(object sender, EventArgs e)
        {
            bool check = this.rdoContactExist.Checked;
            if (!check)
            {
                this.rdoAddrNew.Checked = true;
                //是否选用了新地址
                //如果上面成立, 检查是否有内容
                //如果上面成立, 提示用户
                //再根据结果判断是否清除
                ClearContactTextBoxValue();
            }
            this.txtContactName.ReadOnly = false;
            this.txtContactPhoneNo.ReadOnly = false;
            this.txtContactDiscount.ReadOnly = false;
            this.txtContactAddr.ReadOnly = false;
            ShowContactList(check);
        }

        private void ShowContactList(bool flag)
        {
            this.lblContactList.Visible = flag;
            this.cboContacts.Visible = flag;
        }

        private void ClearContactTextBoxValue()
        {
            this.txtContactName.Clear();
            this.txtContactPhoneNo.Clear();
            this.txtContactDiscount.Clear();
            this.txtContactAddr.Clear();
        }

        private void SetControlState(bool readOnly)
        {
            //this.rdoContactExist.Checked = readOnly;
            this.txtContactName.ReadOnly = readOnly;
            this.txtContactPhoneNo.ReadOnly = readOnly;
            this.txtContactDiscount.ReadOnly = readOnly;
            this.txtContactAddr.ReadOnly = readOnly;
        }

        private void rdoAddrNormal_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rdoContactNew.Checked)
            {
                rdoAddrNew.Checked = true;
            }else
                ShowContactInfo();
        }

        private void rdoContactExist_CheckedChanged(object sender, EventArgs e)
        {
            ShowContactInfo();
            this.rdoAddrNormal.Checked = true;
            this.SetControlState(true);
        }

        private void rdoAddrNew_CheckedChanged(object sender, EventArgs e)
        {
            SetControlState(false);
            this.txtContactName.ReadOnly = true;
        }

        private void txtContactDiscount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.LastIndexOf('.') != -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
        }

        private void btnAddOrderProduct_Click(object sender, EventArgs e)
        {
            //判断 [未实现]
            Product product = new Product();
            if (null != this.cboProducts.SelectedItem)
                product = (Product)this.cboProducts.SelectedItem;
            string productName = product.ProductName;
            string productDimension = this.txtDimension.Text;
            decimal price = decimal.Parse(this.txtPrice.Text);
            int count = (int)this.numericUpDownBuyCount.Value;
            decimal perTotalPrice = price * count;
            int productId = product.ProductId;   

            /*
            DataGridViewRow row = new DataGridViewRow();
            row.SetValues(new object[]{ 
                productName,
                price,
                count, price * count});*/

            dgvOrderProducts.Rows.Add(new object[]{ 
                productId,
                productName,
                productDimension,
                count,
                price,
                perTotalPrice,
            });

            this._totalCount += count;
            this._totalPrice += perTotalPrice;

            UpdateTotal();

            //dgvOrderProducts.Update();

            /*
            DataGridViewCellStyle columnStyle = new DataGridViewCellStyle();
            columnStyle.BackColor = Color.Blue;
            dataGridView2.DefaultCellStyle = columnStyle;
            dataGridView2.RowsDefaultCellStyle = new System.Windows.Forms.DataGridViewCellStyle(columnStyle);
            dataGridView2.ColumnHeadersDefaultCellStyle = columnStyle;
            DataGridViewColumn colProductName = new DataGridViewColumn();
            colProductName.Name = "ProductName";
            colProductName.ValueType = typeof(String);
            DataGridViewColumn colProductPrice = new DataGridViewColumn();
            colProductPrice.Name = "ProductPrice";
            colProductPrice.ValueType = typeof(decimal);
            DataGridViewColumn colProductCount = new DataGridViewColumn();
            colProductCount.Name = "ProductCount";
            colProductCount.ValueType = typeof(int);
            DataGridViewColumn colProductTotalPrice = new DataGridViewColumn();
            colProductTotalPrice.Name = "TotalPrice";
            colProductTotalPrice.ValueType = typeof(decimal);
            dataGridView2.Columns.AddRange(new DataGridViewColumn[] { 
            colProductName, colProductPrice, colProductCount, colProductTotalPrice});
            dataGridView2.Rows.Add(row);
            */


            
        }

        private void dgvOrderProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvOrderProducts.Columns["colBtnDelete"].Index)
            {
                int count = int.Parse(dgvOrderProducts[3, e.RowIndex].Value.ToString());
                decimal tPrice = decimal.Parse(dgvOrderProducts[5, e.RowIndex].Value.ToString());
                dgvOrderProducts.Rows.RemoveAt(e.RowIndex);
                this._totalCount -= count;
                this._totalPrice -= tPrice;
                UpdateTotal();
            }
            
        }

        private void UpdateTotal()
        {
            this.lblTotalCount.Text = string.Format("{0} 件", this._totalCount);
            this.lblTotalPrice.Text = string.Format("{0} 元", this._totalPrice.ToString());
            string mp = this.txtManualPercent.Text;
            if ("0".Equals(mp) || ("0.0").Equals(mp))
                this.lblPercentPrice.Text = this.lblTotalPrice.Text;
            else
            {
                this._percentPrice = this._totalPrice * decimal.Parse(mp);
                this.lblPercentPrice.Text = string.Format("{0} 元", (this._percentPrice * 0.1M).ToString());
            }

        }

        private void chkUsePercent_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUsePercent.Checked)
            {
                string mp = this.txtContactDiscount.Text;
                if ("0".Equals(mp) || ("0.0").Equals(mp))
                    this.lblPercentPrice.Text = this.lblTotalPrice.Text;
                else
                {
                    this._percentPrice = this._totalPrice * decimal.Parse(this.txtManualPercent.Text) * 0.1M;
                    this.lblPercentPrice.Text = string.Format("{0} 元", this._percentPrice.ToString());
                }
                this.txtManualPercent.Text = this.txtContactDiscount.Text;
            }else
            {
                this.txtManualPercent.Text = "0";
                this.lblPercentPrice.Text = this.lblTotalPrice.Text;
            }
        }

        private void txtManualPercent_TextChanged(object sender, EventArgs e)
        {
            string mp = this.txtManualPercent.Text;
            if (string.IsNullOrEmpty(mp))
            {
                this.txtManualPercent.Text = "0";
                this.lblPercentPrice.Text = this.lblTotalPrice.Text;
            }
            else if ("0".Equals(mp) || "0.0".Equals(mp))
            {
                this.lblPercentPrice.Text = this.lblTotalPrice.Text;
            }
            else
            {
                decimal percent = decimal.Parse(this.txtManualPercent.Text);
                this.lblPercentPrice.Text = string.Format("{0} 元", this._totalPrice * percent * 0.1M);
            }
        }

        private void txtManualPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            txtContactDiscount_KeyPress(sender, e);
        }

        private string orderNo = string.Empty;
        private List<string> lstDriver = new List<string>();
        private void SendIntoOfficeWord(string orderNo, string opUser, string contactName, string drivers)
        {
            string companyAddr = "广东清远清新太平麒麟振杰傢俬城";
            string companyPhone = "0763-5770831";
            string docPath = Directory.GetCurrentDirectory() +"\\Order Doc";
            NameValueCollection keyValues = ConfigurationManager.AppSettings;
            if (keyValues.Count == 3)
            { 
                companyAddr = keyValues.Get("Address");
                companyPhone = keyValues.Get("Phone");
                string path = keyValues.Get("DocPath");
                if(!string.IsNullOrEmpty(path.Trim()))
                {
                    if (Directory.Exists(@path))
                        docPath = path;
                }
            }
            if (!Directory.Exists(docPath))
                Directory.CreateDirectory(docPath);

            string renderDate = dtpRender.Value.ToShortDateString();
            //Console.WriteLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToShortTimeString());
            string contactPhone = txtContactPhoneNo.Text;
            string contactAddress = txtContactAddr.Text;
            string contectPostScript = txtPostScript.Text;

            string payType = "支付方式: {0}";
            if (this.rdoPayNow.Checked)
                payType = string.Format(payType, "现金支付");
            else
                payType = string.Format(payType, "货到付款");

            string totalString = string.Empty;//string.Format("数量:{0}件 总价:{1}");
            if(chkUsePercent.Checked)
                totalString = string.Format("数量:{0}件 总价:{1} 折后:{2} {3}", _totalCount, _totalPrice.ToString("C"), this.lblPercentPrice.Text, payType);
            else
                totalString = string.Format("数量:{0}件 总价:{1} {2}", _totalCount, _totalPrice.ToString("C"), payType);
            
            object fileName = string.Format("{0}\\{1}.doc", docPath, DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
            if (File.Exists(fileName.ToString()))
            {
                try
                {
                    File.Delete(fileName.ToString());
                }
                catch (System.IO.IOException)
                {
                    foreach(Process proc in Process.GetProcesses())
                    {
                        if(proc.ProcessName.ToUpper().Equals("WINWORD"))
                        {
                            //if (proc.StartInfo.FileName.Equals(fileName))
                            proc.Kill(); 
                        }
                    }
                }
                
            }

            Microsoft.Office.Interop.Word.ApplicationClass appCls = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Application app = appCls.Application;

            app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;

            object missingValue = Type.Missing;

            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(ref missingValue, ref missingValue, ref missingValue, ref missingValue);



            //doc.Close(ref missingValue, ref missingValue, ref missingValue);

            //app.Quit(ref missingValue);



            object rangeStart = 0;
            object rangeEnd = 0;

            Range range = doc.Range(ref rangeStart, ref rangeEnd);

            Table tblHeader = doc.Tables.Add(range, 3, 3, ref missingValue, ref missingValue);

            //object beforeRow = tblHeader.Rows[1];
            //tblHeader.Rows.Add(ref beforeRow);
            //range(1,1 - 1,3) width 15.56f
            Cell cell = tblHeader.Cell(1, 1);
            cell.Merge(tblHeader.Cell(3, 1));
            tblHeader.PreferredWidth = appCls.CentimetersToPoints(15.62f);
            tblHeader.Columns[1].Width = appCls.CentimetersToPoints(4.13f);

            //tblHeader.Columns[1].SetWidth(4.13f, WdRulerStyle.wdAdjustFirstColumn);
            //cell.SetWidth(15.56f, WdRulerStyle.wdAdjustNone);

            cell = tblHeader.Cell(1, 1);
            //cell.SetWidth(4.13f, WdRulerStyle.wdAdjustNone);
            cell.Range.Text = "麒麟振杰";
            //Microsoft.Office.Interop.Word.FontClass fontIdentity = new Microsoft.Office.Interop.Word.FontClass();
            //fontIdentity.Size = 26f;
            //fontIdentity.Name = "华文彩云";
            //cell.Range.Font = fontIdentity;
            cell.Range.Font.Size = 26f;
            cell.Range.Font.Name = "华文彩云";
            cell.Range.Font.Bold = 1;
            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
            //cell.Range.Cells.Width = 20.13f;

            cell = tblHeader.Cell(1, 2);
            cell.Merge(tblHeader.Cell(3, 2));
            cell.Range.Text = "TM";
            cell.Width = appCls.CentimetersToPoints(1.9f);

            cell = tblHeader.Cell(2, 3);
            cell.Range.Text = string.Format("地址:{0}", companyAddr);
            cell = tblHeader.Cell(3, 3);
            cell.Range.Text = string.Format("电话:{0}", companyPhone);

            tblHeader.Cell(3, 3).Select();

            tblHeader.Columns[3].Width = appCls.CentimetersToPoints(9.52f);


            //tblHeader.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
            //tblHeader.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;

            object WdStory = WdUnits.wdStory;
            app.Selection.EndKey(ref WdStory, ref missingValue);

            object lineNumberNew = 5;

            object WdLine = WdUnits.wdLine;
            object insertRowCount = 1;
            app.Selection.MoveDown(ref WdLine, ref lineNumberNew, ref missingValue);
            app.Selection.TypeParagraph();

            /*
            tblHeader.Select();

            app.Selection.InsertParagraphAfter();

            
            rangeStart = 5;
            rangeEnd = 5;
            range = doc.Range(rangeStart, rangeEnd);


            Paragraph paraghLast = app.Selection.Paragraphs.Last;
            
            //range = paraghLast.Range;
            paraghLast.Range.Select();
             */
            Table tblContact = doc.Tables.Add(app.Selection.Range, 4, 2);
            tblContact.Cell(1, 1).Range.Text = string.Format("订单编号: {0}", orderNo);
            tblContact.Cell(1, 2).Range.Text = string.Format("预计到达日期: {0}", renderDate);

            tblContact.Cell(2, 1).Range.Text = string.Format("收货人: {0}", contactName);
            
            //cell.Width = appCls.CentimetersToPoints(6f);
            tblContact.Cell(2, 2).Range.Text = string.Format("联系电话: {0}", contactPhone);

            tblContact.Cell(3, 1).Range.Text = string.Format("收货地址: {0}", contactAddress);

            tblContact.Cell(4, 1).Merge(tblContact.Cell(4, 2));
            cell = tblContact.Cell(4, 1);
            cell.Range.Text = string.Format("备注: {0}", contectPostScript);
            /*
            Table tblContact = doc.Tables.Add(app.Selection.Range, 4, 1);
            cell = tblContact.Cell(1, 1);
            //cell.Merge(tblContact.Cell(1, 2));
            cell.Range.Text = string.Format("货单编号: {0}", orderNo);

            cell = tblContact.Cell(2, 1);
            object rows = 1;
            object columns = 2;
            cell.Split(ref rows, columns);
            cell = tblContact.Cell(2, 1);
            cell.Range.Text = string.Format("收货人: {0}", contactName);
            //cell.Width = appCls.CentimetersToPoints(6f);
            cell = tblContact.Cell(2, 2);
            cell.Range.Text = string.Format("联系电话: {0}", contactPhone);

            cell = tblContact.Cell(3, 1);
            cell.Range.Text = string.Format("收货地址: {0}", contactAddress);
            
            //可选
            
            cell = tblContact.Cell(4, 1);
            cell.Range.Text = string.Format("备注: {0}", contectPostScript);
            */
            //表格数据
            lineNumberNew = 10;
            app.Selection.MoveDown(ref WdLine, ref lineNumberNew, ref missingValue);
            app.Selection.TypeParagraph();

            //DataGridView dgvOrderProducts = new DataGridView();

            int nameIndex = dgvOrderProducts.Columns["colProductName"].Index;
            int dimensionIndex = dgvOrderProducts.Columns["colProductDimension"].Index;
            int countIndex = dgvOrderProducts.Columns["colCount"].Index;
            int priceIndex = dgvOrderProducts.Columns["colPrice"].Index;

            int rowsCount = dgvOrderProducts.Rows.Count + 2; //列标题1行, 统计1行.
            int colsCount = 4;
            Table tblData = doc.Tables.Add(app.Selection.Range, rowsCount, colsCount);

            //rows = 1;
            //columns = 4;
            //tblData.Cell(1, 1).Split(ref rows, ref columns);
            //table setting
            tblData.Columns[1].Width = app.CentimetersToPoints(3.94f);
            tblData.Columns[2].Width = app.CentimetersToPoints(8f);
            tblData.Columns[3].Width = app.CentimetersToPoints(1.39f);
            tblData.Columns[4].Width = app.CentimetersToPoints(2.22f);
            tblData.Cell(1, 1).Range.Text = "商品名称";
            tblData.Cell(1, 2).Range.Text = "规格";
            tblData.Cell(1, 3).Range.Text = "数量";
            tblData.Cell(1, 4).Range.Text = "单价";
            for (int i = 2, j = 0; i <rowsCount; i++, j++)//预留一行合并
            {
                tblData.Cell(i, 1).Range.Text = dgvOrderProducts[nameIndex, j].Value.ToString();
                tblData.Cell(i, 2).Range.Text = dgvOrderProducts[dimensionIndex, j].Value.ToString();
                tblData.Cell(i, 3).Range.Text = dgvOrderProducts[countIndex, j].Value.ToString();
                tblData.Cell(i, 4).Range.Text = dgvOrderProducts[priceIndex, j].Value.ToString();
            }

            //Add Total;
            tblData.Cell(rowsCount, 1).Merge(tblData.Cell(rowsCount, 4));
            tblData.Cell(rowsCount, 1).Range.Text = totalString;
            tblData.Cell(rowsCount, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            

            //相关负责人
            //设置lineNumberNew

            lineNumberNew = int.Parse(lineNumberNew.ToString()) + rowsCount;

            app.Selection.MoveDown(ref WdLine, ref lineNumberNew, ref missingValue);
            app.Selection.TypeParagraph();

            Table tblRecorder = doc.Tables.Add(app.Selection.Range, 1, 3);
            tblRecorder.Cell(1, 1).Range.Text = string.Format("下单时间: {0}", DateTime.Now.ToString());
            tblRecorder.Cell(1, 2).Range.Text = string.Format("送货员: {0}", drivers);
            tblRecorder.Cell(1, 3).Range.Text = string.Format("操作员: {0}", opUser);
            tblRecorder.Cell(1, 1).Width = app.CentimetersToPoints(5.59f);
            tblRecorder.Cell(1, 2).Width = app.CentimetersToPoints(6.03f);
            tblRecorder.Cell(1, 3).Width = app.CentimetersToPoints(3.93f);

            //global setting

            tblHeader.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
            doc.Select();
            app.Selection.Font.Color = WdColor.wdColorGray60;//RGB(102);

            doc.SaveAs(ref fileName, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);

            ((_Document)doc).Close();

            ((_Application)app).Quit();

            if (chkPreview.Checked)
            {
                Process procWinWord = new Process();
                procWinWord.StartInfo.FileName = fileName.ToString();
                procWinWord.Start();
            }
            else
            {
                appCls = new Microsoft.Office.Interop.Word.ApplicationClass();
                app = appCls.Application;
                doc = app.Documents.Open(ref fileName, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);
                doc.PrintOut(ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);
            }

            toolStripStatusLabelFrmOrder.Text = "打印完毕.";
        }

        private void btnAddDriver_Click(object sender, EventArgs e)
        {
            if (!this.cboDriverChoose.Items.Contains(this.cboDriver.SelectedItem))
            {
                this.cboDriverChoose.Items.Add(this.cboDriver.SelectedItem);
                this.cboDriverChoose.DisplayMember = "EmployeeName";
                this.cboDriverChoose.ValueMember = "EmployeeId";
                this.cboDriverChoose.SelectedIndex = 0;
                lstDriver.Add(((Employee)this.cboDriver.SelectedItem).EmployeeName);
            }
        }

        private void btnRemoveDriverSelected_Click(object sender, EventArgs e)
        {
            this.cboDriverChoose.Items.Remove(this.cboDriverChoose.SelectedItem);
            lstDriver.Add(((Employee)this.cboDriver.SelectedItem).EmployeeName);
        }

        private void dgvOrderProducts_Paint(object sender, PaintEventArgs e)
        {
            if (this.dgvOrderProducts.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvOrderProducts.Rows.Count; )
                {
                    this.dgvOrderProducts.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.RoyalBlue;
                    i += 2;
                }
            }
        }

        private void txtContactDiscount_TextChanged(object sender, EventArgs e)
        {
            if (this.chkUsePercent.Checked)
                chkUsePercent_CheckedChanged(sender, e);
        }

        private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            txtContactDiscount_KeyPress(sender, e);
        }


    }
}
